#include "KeyCountServer.h"

namespace KeyCountServer {

/**
 * 构造函数
 */
Server::Server()
{
    m_socket    = new Socket();
    m_thread    = new Thread();
    m_mutex     = new ThreadMutex();
    m_select    = MAX_THREAD - 1;
    
    for (int i = 0; i < MAX_THREAD; i++)
        m_client[i] = new Client(this, i);
    
    m_onlineList.clear();
}

Server::~Server()
{
    for (int i = 0; i < MAX_THREAD; i++)
        delete m_client[i];
}

bool Server::start()
{
    if (!m_socket->setReuseAddress())
        LOG("set reuse error\n");
    m_thread->start(this, NULL);
    return 1;
}

bool Server::wait()
{
    m_thread->join();
    return 1;
}

void Server::run(Thread *thread, void *arg)
{
    if (!m_socket->bind(SEVR_PORT))
    {
        LOG("bind error\n");
        return;
    }
    if (!m_socket->listen(10))
    {
        LOG("listen error\n");
        return;
    }
    
    for ( ; ; )
    {
        Client *p = getClient();
        if (p == NULL)
        {
            LOG("too many client!\n");
            break;
        }
        Debug(("before client fd = %d", p->m_socket->m_s));
        if (m_socket->accept(*(p->m_socket)) < 0)
        {
            Debug(("select %d client", m_select));
            LOG("accept error\n");
            sleep(1);
            continue;
        }
        Debug(("after client fd = %d", p->m_socket->m_s));
        p->start();
    }
}

Client * Server::getClient()
{
    int pos = m_select;
    
    for ( ; ; )
    {
        pos++;
        if ( pos == MAX_THREAD)
            pos = 0;
        if (pos == m_select)
            break;
        if (!m_client[pos]->isStop())
            continue;
        m_select = pos;
        return m_client[m_select];
    }
    return NULL;
}

}
